package com.digitalchina.lxnsy.base;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.widget.FrameLayout;

import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessConsultDynamic;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.UserXML;
import com.digitalchina.lxnsy.zbsy.EarManagerDetailActivity;
import com.digitalchina.lxnsy.zbsy.TagManageScanActivity;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import butterknife.Bind;
import butterknife.ButterKnife;
import wendu.dsbridge.DWebView;


/**
 * ================================================
 * 项目名称：bigdata
 * 类描述：
 * 包名：com.digitalchina.bzas.activity
 * 创建人：郑皓
 * 创建时间：2018/12/3 13:59
 * 修改备注：
 * ================================================
 */

public abstract class BaseHtmlActivity extends BaseActivity {

    protected final int REQUEST_CODE_1 = 111;

    /** 视频全屏参数 */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private IX5WebChromeClient.CustomViewCallback customViewCallback;
    @Bind(R.id.webView)
    protected DWebView webView;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_base_html);

        // set debug mode
        DWebView.setWebContentsDebuggingEnabled(false);
        webView.addJavascriptObject(new JsApiBase(), "base");

        com.tencent.smtt.sdk.WebSettings webSettings=webView.getSettings();
        //允许webview对文件的操作
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccessFromFileURLs(true);

        webSettings.setAllowFileAccess(true); // 允许访问文件
        webSettings.setSupportZoom(true); // 支持缩放
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setCacheMode(com.tencent.smtt.sdk.WebSettings.LOAD_NO_CACHE); // 不加载缓存内容

        //用于js调用Android
        webSettings.setJavaScriptEnabled(true);
        //设置编码方式
        webSettings.setDefaultTextEncodingName("utf-8");

        com.tencent.smtt.sdk.WebChromeClient wvcc = new com.tencent.smtt.sdk.WebChromeClient();
        webView.setWebChromeClient(wvcc);

        WebViewClient wvc = new com.tencent.smtt.sdk.WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                webView.loadUrl(url);
                return true;
            }
        };
        webView.setWebViewClient(wvc);

        webView.setWebChromeClient(new com.tencent.smtt.sdk.WebChromeClient() {

            /*** 视频播放相关的方法 **/

            @Override
            public View getVideoLoadingProgressView() {
                FrameLayout frameLayout = new FrameLayout(activity);
                frameLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                return frameLayout;
            }

            @Override
            public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback callback) {
                showCustomView(view, callback);
            }

            @Override
            public void onHideCustomView() {
                hideCustomView();
            }
        });

        loadHtml();
    }

    /** 视频播放全屏 **/
    private void showCustomView(View view, IX5WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /** 隐藏视频全屏 */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        webView.setVisibility(View.VISIBLE);
    }

    /** 全屏容器界面 */
    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(BaseHtmlActivity ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                /** 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面 */
                if (customView != null) {
                    hideCustomView();
                } else if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }

    protected abstract void loadHtml();


    protected void loadUrl(String name) {
        webView.loadUrl("file:///android_asset/dist/" + name + ".html");
    }

    protected void callJsMethod(String method) {
        webView.callHandler(method, new String[]{""});
    }

    protected void callJsMethod(String method, String[] agrs) {
        webView.callHandler(method, agrs);
    }

    @Override
    public void initMember() {

    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case 1011:
                        callBack(msg.obj);
                        break;
                    case 1012:
                        showToast(msg.obj.toString());

                        break;
                }
            }
        };

    }

    @Override
    public void callBack(Object object) {


        callJsMethod("backScanData",new String[]{object.toString()});


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    public class JsApiBase {

        @JavascriptInterface
        public String getServer(Object msg) {
            return URL.SERVER;
        }

        @JavascriptInterface
        public void logNative(Object msg) {
            LogUtils.e(msg);
        }

        @JavascriptInterface
        public String getUserId(Object msg) {
            return UserXML.getUserId(activity);
        }


        @JavascriptInterface
        public String getLOGINJs(Object msg) {
            return UserXML.getLOGIN(activity);
        }

        @JavascriptInterface
        public String getSECURELOGINJs(Object msg) {
            return UserXML.getSecureLogin(activity);
        }

        @JavascriptInterface
        public String getUserTypeJs(Object msg) {
            return UserXML.getUserType(activity);
        }


        @JavascriptInterface
        public void showToastJs(Object msg) {
            showToast(msg.toString());
        }

        @JavascriptInterface
        public void cancelDialogJs(Object msg) {
            dismissDialog();
        }

        @JavascriptInterface
        public void showDialogJs(Object msg) {
            if (msg == null || msg.equals("") || msg.toString().equals("null"))
                msg = "加载中...";
            showDialog(msg.toString());
        }

        @JavascriptInterface
        public void showAlertJs(Object msg) {
            CustomDialog.nativeDialog(activity, msg.toString());
        }

        @JavascriptInterface
        public void showAlertCloseJs(Object msg) {
            CustomDialog.nativeDialogFinish(activity, msg.toString());
        }

        @JavascriptInterface
        public void closeJs(Object msg) {
            finish();
        }

        @JavascriptInterface
        public void closePage(Object msg) {
            finish();
        }



        @JavascriptInterface
        public void scanOneScan(Object msg) {

            String chipNo="E2806894000040093CB2410E";

            BusinessConsultDynamic.queryDetail(activity, chipNo,mHandler);


     //       GotoUtil.gotoForResultActivity(activity, TagManageScanActivity.class, REQUEST_CODE_1);




        }

    }

    @Override
    public void onPause() {
        super.onPause();
        webView.onPause();
        webView.pauseTimers();
    }

    @Override
    public void onResume() {
        super.onResume();
        webView.resumeTimers();
        webView.onResume();
    }


    @Override
    protected void onDestroy() {
        webView.destroy();
        webView = null;
        super.onDestroy();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            String chipNo = (String) data.getSerializableExtra("chipNo");
            if(!StringUtil.isStrEmpty(chipNo)){
                BusinessConsultDynamic.queryDetail(activity, chipNo,mHandler);

            }
        }
    }


}
